package com.rongxun.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.rongxun.hbwallet.R;

import java.text.DecimalFormat;

/**
 * 创建者     庄丰泽
 * 创建时间   2018/7/20 16:35
 * 描述
 */
public class SportProgressView extends View {
    private static final int   DEFAULT_MIN_WIDTH    = 200; //View默认大小
    //圆弧的宽度
    private static final float DEFAULT_BORDER_WIDTH = 25f;
    //小原点的半径
    private              int   DEFAULT_LITLE_WIDTH  = dipToPx(5);

    private ValueAnimator progressAnimator;
    private float  textSize        = dipToPx(22);
    private float  BIM_textSize    = dipToPx(16);
    private float  Number_textSize = dipToPx(42);
    private int    padding         = dipToPx(10);//默认胖和瘦距离上面圆环的距离
//    private int    marging         = (int) (Math.max(DEFAULT_BORDER_WIDTH, textSize));
    private float  marging_radian  = dipToPx(5);
    private int    marging         = (int) (Math.max(DEFAULT_BORDER_WIDTH, marging_radian));
    private float  currentAngle    = 0;
    private String PANG_NUMBER     = "";
    //当前的分数
    private float  maxCount        = 50;
    private float  currentCount    = 0;
    private float  startAngle      = 140;//开始绘制的角度
    private float  lastAngle       = 260;//最后绘制的角度

    private int aniSpeed = 1000;//设置滚动的速度
    private Context mContext;
    DecimalFormat df = new DecimalFormat("0.0");//格式化小数，不足的补0



    public SportProgressView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SportProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
    }



    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);


        Paint paintDefalt = new Paint();
        paintDefalt.setColor(getResources().getColor(R.color.white_a70));
        //设置笔刷的样式 Paint.Cap.Round ,Cap.SQUARE等分别为圆形、方形
        paintDefalt.setStrokeCap(Paint.Cap.SQUARE);
        float borderWidth = DEFAULT_BORDER_WIDTH;//圆弧宽度

        float centerX = (getHeight() - 2 * marging) / 2;
        RectF oval1 = new RectF(marging, marging, 2 * centerX + marging, 2 * centerX + marging);
        /**
         * Paint.Style.FILL    :填充内部
         Paint.Style.FILL_AND_STROKE  ：填充内部和描边
         Paint.Style.STROKE  ：仅描边
         */
        paintDefalt.setStyle(Paint.Style.STROKE);//设置填充样式
        paintDefalt.setAntiAlias(true);//抗锯齿功能
        paintDefalt.setStrokeWidth(borderWidth);//设置画笔宽度
        paintDefalt.setStrokeCap(Paint.Cap.ROUND);


        /**
         * drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint)//画弧，
         参数一是RectF对象，一个矩形区域椭圆形的界限用于定义在形状、大小、电弧，
         参数二是起始角(度)在电弧的开始，
         参数三扫描角(度)开始顺时针测量的，参数四是如果这是真的话,包括椭圆中心的电弧,并关闭它,如果它是假这将是一个弧线,参数五是Paint对象；
         */
        //绘制默认灰色的圆弧
        canvas.drawArc(oval1, 140, 260, false, paintDefalt);//小弧形
        // 参数一为渐变起初点坐标x位置，参数二为y轴位置，参数三和四分辨对应渐变终点，最后参数为平铺方式，这里设置为镜像.
        //2-----绘制当前进度的圆弧
        Paint paintCurrent = new Paint();
        paintCurrent.setStyle(Paint.Style.STROKE);//设置填充样式
        paintCurrent.setColor(mContext.getResources().getColor(R.color.white));
        paintCurrent.setAntiAlias(true);//抗锯齿功能
        paintCurrent.setStrokeWidth(borderWidth);//设置画笔宽度
        paintCurrent.setStrokeCap(Paint.Cap.ROUND);
        // 创建SweepGradient对象
        // 第一个,第二个参数中心坐标
        // 后面的参数与线性渲染相同

        //当前进度
        canvas.drawArc(oval1, startAngle, currentAngle, false, paintCurrent);

        //内容显示文字
        Paint vTextPaint = new Paint();
        vTextPaint.setTextSize(textSize);
        vTextPaint.setColor(mContext.getResources().getColor(R.color.dark_grey));
        vTextPaint.setAntiAlias(true);//抗锯齿功能
        vTextPaint.setTextAlign(Paint.Align.CENTER);
        //圆环中心的文字
        vTextPaint.setTextSize(BIM_textSize);
        canvas.drawText("步数", getWidth() / 2, (int) ((centerX + marging) / 3 * 1.5 + BIM_textSize), vTextPaint);
        vTextPaint.setTextSize(Number_textSize);
        Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
        vTextPaint.setTypeface(font);
        vTextPaint.setColor(mContext.getResources().getColor(R.color.white));
        canvas.drawText(PANG_NUMBER, getWidth() / 2, (int) ((centerX + marging) + BIM_textSize), vTextPaint);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measure(widthMeasureSpec, true), measure(heightMeasureSpec, false));
    }

    /**
     * @param origin
     * @param isWidth
     * @return
     */
    private int measure(int origin, boolean isWidth) {
        int result = DEFAULT_MIN_WIDTH;
        int specMode = MeasureSpec.getMode(origin);//得到模式
        int specSize = MeasureSpec.getSize(origin);//得到尺寸

        switch (specMode) {
            //EXACTLY是精确尺寸，当我们将控件的layout_width或layout_height指定为具体数值时如andorid:layout_width="50dip"，或者为FILL_PARENT是，都是控件大小已经确定的情况，都是精确尺寸。
            case MeasureSpec.EXACTLY:
                //AT_MOST是最大尺寸，当控件的layout_width或layout_height指定为WRAP_CONTENT时，控件大小一般随着控件的子空间或内容进行变化，此时控件尺寸只要不超过父控件允许的最大尺寸即可
            case MeasureSpec.AT_MOST:
                result = specSize;
                if (isWidth) {
                    //                    widthForUnspecified = result;
                } else {
                    //                    heightForUnspecified = result;
                }
                break;
            //UNSPECIFIED是未指定尺寸，这种情况不多，一般都是父控件是AdapterView，通过measure方法传入的模式。
            case MeasureSpec.UNSPECIFIED:
            default:
                result = Math.min(result, specSize);
                if (isWidth) {//宽或高未指定的情况下，可以由另一端推算出来 - -如果两边都没指定就用默认值
                    //                    result = (int) (heightForUnspecified * BODY_WIDTH_HEIGHT_SCALE);
                } else {
                    //                    result = (int) (widthForUnspecified / BODY_WIDTH_HEIGHT_SCALE);
                }
                if (result == 0) {
                    result = DEFAULT_MIN_WIDTH;
                }
                break;
        }

        return result;
    }

    /**
     * dip 转换成px
     *
     * @param dip
     * @return
     */
    private int dipToPx(float dip) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1));
    }

    /***
     * 设置当前的进度值
     *
     * @param currentCounts
     */
    public void setCurrentCount(float currentCounts) {

        float curren = Float.parseFloat(df.format(currentCounts / maxCount));//返回的是String类型的
        float last_angle = 180 * (curren > 1 ? 1 : curren);//最后要到达的角度
        PANG_NUMBER = (int) currentCounts + "";//肥胖指数的设置
        lastAngle = currentAngle;//保存最后绘制的位置
        setAnimation(lastAngle, last_angle, aniSpeed);
    }

    /**
     * 为进度设置动画
     *
     * @param last
     * @param current
     */
    private void setAnimation(float last, float current, int length) {
        progressAnimator = ValueAnimator.ofFloat(last, current);
        Log.e("last=====", last + "");
        Log.e("current=====", current + "");
        progressAnimator.setDuration(length);

        progressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                currentAngle = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
        progressAnimator.start();
    }
}
